package com.alan.service.impl;

import com.alan.entity.RestBean;
import com.alan.service.OssUploadService;
import com.alan.util.PathUtils;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


@Service
public class OssUploadServiceImpl implements OssUploadService {

    @Value("${oss.ak}")
    private String ak;
    @Value("${oss.sk}")
    private String sk;
    @Value("${oss.bucket}")
    private String bucket;
    @Value("${oss.domainName}")
    private String domainName;




    @Override
    public RestBean loadImg(MultipartFile img) {
        //判断文件类型
        if (!(img.getOriginalFilename().endsWith(".jpg")||
                img.getOriginalFilename().endsWith(".png"))){
            //文件类型不合法
            //TODO:需要统一异常处理
            throw new RuntimeException("出错了");
        }
        //判断成功，上传到七牛云
        //生成路径
        String filePath = PathUtils.generateFilePath(img.getOriginalFilename());
        String url = uploadOss(img,filePath);
        return RestBean.success(url);
    }

    /**
     *		核心方法：将文件上传到oss，并返回一个外链（URL）供客户访问
     */
    private String uploadOss(MultipartFile file, String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
//        String accessKey = "oaBRDbsZbp4HaLOAq-c9FMxpMY_MpDdmJzic9-hm";
//        String secretKey = "pePYT4hZ62gS5Wv8ut-Fpt0eeRobce-Mxo1q1IJ3";
//        String bucket = "alan223";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filePath;//指定文件名

        try {
 /*           byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);*/
            InputStream inputStream = file.getInputStream();
            Auth auth = Auth.create(ak, sk);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://"+domainName+"/"+key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://"+domainName+key;
    }
}